/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Model.Category;
import Model.User;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import javax.swing.JOptionPane;

/**
 *
 * @author Admin
 */
public class ServerCore extends Thread {

    Socket cs;
    ObjectInputStream inObject;
    ObjectOutputStream outObject;
    ServerReader serverReader;
    ServerBook serverBook;
    ServerIssue serverIssue;
    ServerCategory serverCategory;
    MyConnect myConnect;

    public ServerCore() {
    }

    public ServerCore(Socket cs) {
        try {
            this.cs = cs;
            inObject = new ObjectInputStream(new DataInputStream(cs.getInputStream()));
            outObject = new ObjectOutputStream(new DataOutputStream(cs.getOutputStream()));

            serverBook = new ServerBook(inObject, outObject);

            serverReader = new ServerReader(inObject, outObject);

            serverIssue = new ServerIssue(inObject, outObject);
            serverCategory = new ServerCategory(inObject, outObject);
            myConnect = new MyConnect(inObject, outObject);

        } catch (Exception ex) {

            JOptionPane.showMessageDialog(null, "getConnect: " + ex.getMessage());
        }

    }

    @Override
    public void run() {
        try {
            while (true) {
                String request = (String) inObject.readObject();
                switch (request) {
                    case "exit":
                        inObject.close();
                        outObject.close();
                        cs.close();
                        System.out.println("client closed!");
                        return;
                    case "login":
                        login();
                        break;
                    case "showMyAccount":
                        myConnect.showMyAccount();
                        break;
                    case "changePassword":
                        myConnect.changePassword();
                        break;
                    case "showAllBook":
                        serverBook.showBook();
                        break;
                    case "deleteBook":
                        serverBook.deleteBook();
                        break;
                    case "editBook":
                        serverBook.editBook();
                        break;
                    case "searchBookID":
                        serverBook.searchBookID();
                        break;
                    case "searchTitleOrCategory":
                        serverBook.searchTitleOrCategory();
                        break;
                    case "searchAuthor":
                        serverBook.searchAuthor();
                        break;
                    case "insertBook":
                        serverBook.insertBook();
                        break;
                    case "showAllReader":
                        serverReader.showAllReader();
                        break;
                    case "deleteReader":
                        serverReader.deleteReader();
                        break;
                    case "editReader":
                        serverReader.editReader();
                        break;
                    case "insertReader":
                        serverReader.addReader();
                        break;
                    case "searchReaderID":
                        serverReader.searchReaderID();
                        break;    
                    case "insertCategory":
                        serverCategory.controlAddCategory();
                        break;
                    case "getCategoryName":
                        getCategoryName();
                        break;
                    case "editCategory":
                        serverCategory.editCategory();
                        break;
                  
                    
                        
                        //IssueNote
                    case "ShowBookToIssue":
                        serverBook.showBookBorrow();
                        break;
                    case "BorrowBook":
                        serverIssue.controlBorrow();
                        break;
                    case "ShowIssueNoteReturn":
                        serverIssue.ControlShowAllIssueNote(0);//Hien trong phan return nen se khong hien nhug phieu tra roi
                        break;
                    case "ShowIssueNoteReport":
                        serverIssue.ControlShowAllIssueNote(1);//Hien tat ca cac phieu muon dang luu trong csdl
                        break;
                    case "CheckFine":
                        serverIssue.CheckFine();
                        break;
                    case "ReturnBook":
                        serverIssue.controlReturnBook();
                        break;
                    case "SearchIssue":
                        serverIssue.ControlSearchIssue();
                        break;
                    case "SearchTitle":
                        serverIssue.ControlSearchTitle();
                        break;
                    case "SearchFullName":
                        serverIssue.ControlSearchFullName();
                        break;
                    default:
                        JOptionPane.showMessageDialog(null, request);
                        break;                                          
                }
            }
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex);


         //  JOptionPane.showMessageDialog(null,"Error on Server : "+ ex);
        }         

    }

    private void login() {

        try {
            User user = (User) inObject.readObject();//nhan doi tuong login do client goi
            MyConnect conn = new MyConnect();
            outObject.writeObject(conn.isAuthentication(user));      //goi thong bao cho client                
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }

    }

    private void getCategoryName() {
        try {
            outObject.writeObject(serverCategory.getDataCategoryName());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    static private void configConnectDatabase() {
        Scanner in = new Scanner(System.in);
        String Address;
        String Port;
        String DatabaseName;
        String Username;
        String Password = null;
        boolean completed = false;
        while (!completed) {
            if (!MyConnect.connecting()) {
                System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
                System.out.println("        Information connect Database");
                System.out.print("      Address database: ");
                Address = in.nextLine();
                System.out.print("      Port: ");
                Port = in.nextLine();
                System.out.print("      DatabaseName: ");
                DatabaseName = in.nextLine();
                System.out.print("      Username database: ");
                Username = in.nextLine();
                System.out.print("      Password database: ");
                Password = in.nextLine();
                char[] Pass = Password.toCharArray();
                if (MyConnect.saveConfig(Address, Port, DatabaseName, Username, Pass)) {
                    System.out.println("Information connect database saved completed");
                    completed = true;
                }
            }
            else{
                completed=true;
            }
        }
    }

    public static void main(String[] args) throws Exception {   
        configConnectDatabase();
        ServerSocket ss = new ServerSocket(1234);
        while (true) {//vong lap de chap nhan nhieu ket noi
            //cho va chap nhan kn tu client, cs la socket dung de goi nhan dl voi client.
            System.out.println("Dang cho client ket noi...");
            Socket cs = ss.accept();
            System.out.println("Da chap nhan ket noi cua client\n");
            new ServerCore(cs).start(); //tao thread phuc vu client
        }
    }
}
